package com.coms.gateway.config;
import com.alibaba.fastjson.JSON;
import com.clms.common.JwtUtils;
import com.clms.common.R;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;
import org.springframework.core.io.buffer.DataBuffer;

import javax.annotation.Resource;
import java.nio.charset.StandardCharsets;

/**
 * @program: clms-third
 * @description:
 * @author: 大鱼
 * @create: 2021-07-21 13:55
 **/

public class LoginFilter implements GlobalFilter, Ordered {
    @Resource
    private RsaKeyProperties rsaKeyProperties;
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        String token = request.getHeaders().getFirst("token");
        if(StringUtils.isNotEmpty(token))
        {
            if (JwtUtils.getInfoFromToken(token, rsaKeyProperties.getPublicKey())!=null) {
                return chain.filter(exchange);

            }
        }
        String Path = request.getPath().toString();
        if (Path.contains("/system/login")) {

            return chain.filter(exchange);
        }
        DataBuffer buffer = null;
        try{
            byte[] datas = JSON.toJSONString(R.error().message("请先登录")).getBytes(StandardCharsets.UTF_8);
             buffer = response.bufferFactory().wrap(datas);
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            response.getHeaders().add("Content-Type", "application/json;charset=UTF-8");
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }

        return response.writeWith(Mono.just(buffer));
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
